import React, { useState } from 'react';
import * as XLSX from 'xlsx';
import './DataLoader.css';

function DataLoader({ setData }) {
  const [file, setFile] = useState(null);
  const [sheets, setSheets] = useState([]);
  const [selectedSheet, setSelectedSheet] = useState('');
  const [columns, setColumns] = useState([]);
  const [selectedColumn, setSelectedColumn] = useState('');
  const [startRow, setStartRow] = useState(1);
  const [endRow, setEndRow] = useState(100);
  const [previewData, setPreviewData] = useState({ head: [], tail: [] });
  const [isLoading, setIsLoading] = useState(false);

  const handleFileChange = (e) => {
    const selectedFile = e.target.files[0];
    if (!selectedFile) return;

    setFile(selectedFile);
    const reader = new FileReader();
    
    reader.onload = (e) => {
      const data = new Uint8Array(e.target.result);
      const workbook = XLSX.read(data, { type: 'array' });
      const sheetNames = workbook.SheetNames;
      setSheets(sheetNames);
      setSelectedSheet(sheetNames[0]);
    };
    
    reader.readAsArrayBuffer(selectedFile);
  };

  const handleSheetChange = async (e) => {
    const sheetName = e.target.value;
    setSelectedSheet(sheetName);
    
    if (!file) return;
    
    setIsLoading(true);
    const data = await readExcelSheet(file, sheetName);
    
    if (data.length > 0) {
      const firstRow = data[0];
      const cols = Object.keys(firstRow).filter(key => !isNaN(parseInt(firstRow[key])) || firstRow[key] === undefined);
      setColumns(cols);
      setSelectedColumn(cols[0]);
    }
    setIsLoading(false);
  };

  const readExcelSheet = (file, sheetName) => {
    return new Promise((resolve) => {
      const reader = new FileReader();
      
      reader.onload = (e) => {
        const data = new Uint8Array(e.target.result);
        const workbook = XLSX.read(data, { type: 'array' });
        const worksheet = workbook.Sheets[sheetName];
        const jsonData = XLSX.utils.sheet_to_json(worksheet);
        resolve(jsonData);
      };
      
      reader.readAsArrayBuffer(file);
    });
  };

  const handlePreview = async () => {
    if (!file || !selectedSheet) return;
    
    setIsLoading(true);
    const data = await readExcelSheet(file, selectedSheet);
    
    if (data.length > 0) {
      const numericData = data
        .slice(startRow - 1, endRow)
        .map(row => parseInt(row[selectedColumn]))
        .filter(num => !isNaN(num) && num >= 0 && num <= 9);
      
      setPreviewData({
        head: numericData.slice(0, 10),
        tail: numericData.slice(-10)
      });
    }
    setIsLoading(false);
  };

  const handleLoadData = async () => {
    if (!file || !selectedSheet) return;
    
    setIsLoading(true);
    const data = await readExcelSheet(file, selectedSheet);
    
    if (data.length > 0) {
      const numericData = data
        .slice(startRow - 1, endRow)
        .map(row => parseInt(row[selectedColumn]))
        .filter(num => !isNaN(num) && num >= 0 && num <= 9);
      
      setData(numericData);
      
      setPreviewData({
        head: numericData.slice(0, 10),
        tail: numericData.slice(-10)
      });
    }
    setIsLoading(false);
  };

  return (
    <div className="card">
      <h2>Data Loader</h2>
      
      <div className="form-group">
        <label>Excel File</label>
        <input 
          type="file" 
          accept=".xlsx,.xls" 
          onChange={handleFileChange} 
        />
      </div>
      
      {sheets.length > 0 && (
        <div className="form-group">
          <label>Worksheet</label>
          <select 
            value={selectedSheet} 
            onChange={handleSheetChange}
            disabled={isLoading}
          >
            {sheets.map(sheet => (
              <option key={sheet} value={sheet}>{sheet}</option>
            ))}
          </select>
        </div>
      )}
      
      {columns.length > 0 && (
        <div className="form-group">
          <label>Data Column</label>
          <select 
            value={selectedColumn} 
            onChange={(e) => setSelectedColumn(e.target.value)}
            disabled={isLoading}
          >
            {columns.map(col => (
              <option key={col} value={col}>{col}</option>
            ))}
          </select>
        </div>
      )}
      
      <div className="form-group">
        <label>Start Row</label>
        <input 
          type="number" 
          min="1" 
          value={startRow} 
          onChange={(e) => setStartRow(parseInt(e.target.value) || 1)}
          disabled={isLoading}
        />
      </div>
      
      <div className="form-group">
        <label>End Row</label>
        <input 
          type="number" 
          min="1" 
          value={endRow} 
          onChange={(e) => setEndRow(parseInt(e.target.value) || 100)}
          disabled={isLoading}
        />
      </div>
      
      <div className="button-group">
        <button 
          className="button" 
          onClick={handlePreview}
          disabled={!file || isLoading}
        >
          {isLoading ? 'Loading...' : 'Preview Data'}
        </button>
        
        <button 
          className="button" 
          onClick={handleLoadData}
          disabled={!file || isLoading}
        >
          {isLoading ? 'Loading...' : 'Load Data'}
        </button>
      </div>
      
      {(previewData.head.length > 0 || previewData.tail.length > 0) && (
        <div className="preview-container">
          <h3>Data Preview</h3>
          <p>First 10 values: {previewData.head.join(', ')}</p>
          <p>Last 10 values: {previewData.tail.join(', ')}</p>
          <p>Total loaded: {previewData.head.length + previewData.tail.length} values</p>
        </div>
      )}
    </div>
  );
}

export default DataLoader;